package com.systemCapacity.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.systemCapacity.common.dto.LoginDto;
import com.systemCapacity.common.lang.Result;
import com.systemCapacity.entity.User;
import com.systemCapacity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

@RestController
public class LoginController {

    private static final int ONLINE = 1;

    private static final int OFFLINE = 2;

    @Autowired
    UserService userService;

    /**
     * 用户登录
     * @param loginDto 用户登录结构
     * @param response 登陆结果
     * @return 登陆结果
     */
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {

        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        Assert.notNull(user, "用户不存在");

        if(!user.getPassword().equals(loginDto.getPassword())){
            return Result.fail("密码不正确");
        }

//        if (user.getStatus() == ONLINE) {
//            return Result.fail("当前用户已登录");
//        }

        // 更新用户在线状态
        LambdaUpdateWrapper<User> userLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        userLambdaUpdateWrapper.eq(User::getId, user.getId())
                .set(User::getStatus, ONLINE)
                .set(User::getLastLogin, LocalDateTime.now());

        userService.update(null, userLambdaUpdateWrapper);

        return Result.succ(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .map()
        );
    }

    /**
     * 用户退出
     * @param id 用户id
     * @return 退出结果
     * @throws Exception 查询错误
     */
    @GetMapping("/logout/{id}")
    public Result logout(@PathVariable(name = "id") int id) throws Exception {
        // 查询用户是否存在或上线
        User user = userService.getById(id);
        Assert.notNull(user, "该用户不存在");
        if (user.getStatus() == OFFLINE) {
            return Result.fail("用户未上线");
        }
        // 更新用户在线状态
        LambdaUpdateWrapper<User> userLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        userLambdaUpdateWrapper.eq(User::getId, user.getId())
                .set(User::getStatus, OFFLINE)
                .set(User::getLastLogout, LocalDateTime.now());
        userService.update(null, userLambdaUpdateWrapper);
        return Result.succ(null);
    }
}
